import { IStackStyles, Stack } from '@fluentui/react';
import { useBoolean } from '@fluentui/react-hooks';
import { useEffect, useState } from 'react';
import { Route, Routes, useLocation, useNavigate } from 'react-router';
import Alymodel from '../../mysql_interface/model';
import { asyncgetcoursecatebag, asyncgetktUser, asyncgetteam, asyncselectUsercourse, getAllCatebag, getAllCatebagtype, getallcourse, session } from '../api/api';
import login from '../utils/login';
import Catebagview from '../view/Catebag';
import CouresView from '../view/Course';
import DownloadView from '../view/download';
import Login from '../view/login';
import Home from './home';
import { Nav } from './nav';
import { maxLimit } from '../utils/data';
const stackStyles: Partial<IStackStyles> = {
  root: {
    textAlign: 'center',
    color: '#fff',
    backgroundColor: '#f0f4fe', // 导航栏背景图 #fff
    height: '64px',
    '--el-header-height': '64px'
  },
};
const stackStyles2: Partial<IStackStyles> = {
  root: {
    '--el-header-height': '64px',
  },
};

function getThirdLevelDomain() {
  // 获取完整的主机名
  const hostname = window.location.hostname;
  // 分割主机名，得到各个级别的域名
  const domains = hostname.split('.');
  // 检查是否有三个或更多级别的域名
  if (domains.length > 2) {
    // 获取三级域名，即数组的第二个元素
    const thirdLevelDomain = domains[0];
    return thirdLevelDomain;
  } else {
    // 如果没有三级域名，则返回null或相应的提示信息
    return null;
  }
}

export default function App() {
  const [user, setuser] = useState<Alymodel.IMuser>()
  const [getCatebag, setCatebag] = useState<Alymodel.IMcatebag[]>([])
  const [getCatebagtype, setCatebagtype] = useState<Alymodel.IMcatebagtype[]>([])
  const [getCourse, setCourse] = useState<Alymodel.IMcourse[]>([])
  const [getuserCourse, setuserCourse] = useState<Alymodel.IMcourse[]>([])
  const [getuserUserCourse, setuserUserCourse] = useState<Alymodel.IMusercourse[]>([])
  const [getCoursecatebag, setCoursecatebag] = useState<Alymodel.IMcoursecatebag[]>([])
  const [isModalOpen, { setTrue: showModal, setFalse: hideModal }] = useBoolean(false);
  const navigator = useNavigate()
  const location = useLocation()

  const [teamid, setTeamID] = useState({});
  useEffect(() => {
    // 使用URL search params API可以方便地获取地址栏中的参数
    const searchParams = new URLSearchParams(window.location.search);
    const params: { teamid: number } = { ...Array.from(searchParams.entries()).reduce((acc, [key, value]) => ({ ...acc, [key]: value }), { teamid: 0 }) }
    // 根据域名获取 teamid
    const teamkey = getThirdLevelDomain()
    if (teamkey) {
      try {
        asyncgetteam(teamkey).then((e: { ID: number }) => { setTeamID(e.ID) })
      } catch (error) {
        // 找不到
        setTeamID(params.teamid)
        console.error("getTeamInfo=>", error)
      }
    } else {
      setTeamID(params.teamid)
    }
    // console.log("teamid=>", teamid)
    // console.log("params=>", params)
  }, []);

  useEffect(() => {
    session().then(e => {
      setuser(e)
      if (location.pathname === '/') {
        navigator('/secure/myclass')
      }
    }).catch(f => {
      login(navigator)
    })
    return () => { }
  }, [true])

  useEffect(() => {
    if (user) {
      // 获取所有课程组
      getAllCatebag({}).then(e => {
        if ([121649, 113417].includes(Number(user.userid))) {
          let data = e.filter(e => !e.name?.toLocaleLowerCase().includes('noip')).filter(e => !e.name?.toLocaleLowerCase().includes('省选'))
          if ([121649].includes(Number(user.userid))) {
            data = data.filter(e => !['信息学名师工作室', 'C++课程语言基础'].includes(String(e.name).toLocaleUpperCase()))
          }
          setCatebag(data)
        } else {
          setCatebag(e)
        }
      })
      // 类别
      getAllCatebagtype({}).then(e => {
        const data = e.sort((a, b) => Number(a.paixu) - Number(b.paixu))
        setCatebagtype(data)
      })
      getallcourse({ _limit: maxLimit }).then(e => {
        setCourse(e)
      })
      // 获取用户课程关系(user_ID-course_ID)使用的新接口 /studycode/v2/team/selectUsercourse
      asyncselectUsercourse({
        user_ID: user.userid,
        teamid: teamid,
      }).then(ret => {
        const userCourseMap = user?.userid ? ret[user?.userid] || [] : []
        setuserUserCourse(userCourseMap)
        // 获取用户课程-课程表
        asyncgetktUser({}).then(e => {
          // 根据关系表 筛选课程
          let myCourse = e.filter(e => {
            return userCourseMap.find(uc => uc.course_ID === e.ID)
          })
          setuserCourse(myCourse)
        })
      })
      // 查询所有课程包课程
      asyncgetcoursecatebag({ _limit: maxLimit }).then(e => {
        setCoursecatebag(e)
      })
      if (location.pathname === '/') {
        navigator('/secure/myclass')
      }
    }
  }, [user])

  return (
    <Stack style={{ backgroundColor: '#f0f4fe' }} styles={stackStyles2}>
      <Stack styles={stackStyles}>
        <Nav getuser={user} setshow={showModal} setuser={setuser} ></Nav>
      </Stack>
      <Routes>
        {/* 我的课堂 */}
        <Route path="/secure/myclass" element={
          <Home getuser={user} getCatebag={getCatebag} getCatebagtype={getCatebagtype} getCourse={getCourse} getuserCourse={getuserCourse} getuserUserCourse={getuserUserCourse} getCoursecatebag={getCoursecatebag} />
        } >
        </Route>
        <Route path="/catebag/:ID"
          element={<Catebagview getuser={user} getCatebag={getCatebag} getCatebagtype={getCatebagtype} getCourse={getCourse} getuserCourse={getuserCourse} getuserUserCourse={getuserUserCourse} getCoursecatebag={getCoursecatebag} ></Catebagview>}
        >
        </Route>
        <Route path="/course/:ID"
          element={<CouresView getuser={user} getCatebag={getCatebag} getCatebagtype={getCatebagtype} getCourse={getCourse} getuserCourse={getuserCourse} getuserUserCourse={getuserUserCourse} getCoursecatebag={getCoursecatebag} ></CouresView>}
        >
        </Route>
        <Route path="/secure/download" element={<DownloadView />

        } />
        <Route path="/login" element={<Login isModalOpen={isModalOpen} hideModal={hideModal} setuser={setuser} />
        } />
      </Routes>
    </Stack>
  )
}


